<?php
//$code = new Code();
//$code->show();
class Code{
	private $img;//资源
	private $bgColor;
	private $fontColor;
	private $fontSize;
	private $codeLen;
	private $width;
	private $height;
	private $seed;
	private $fontFile;

	/**
	 * [__construct 初始化构造函数]
	 * @param [type] $codeLen   [验证码长度]
	 * @param [type] $width     [验证码宽度]
	 * @param [type] $height    [验证码高度]
	 * @param [type] $fontColor [字体颜色]
	 * @param [type] $fontSize  [字体大小]
	 * @param [type] $bgColor   [背景颜色]
	 */
	public function __construct($codeLen = NULL,$width = NULL,$height = NULL, $fontColor = NULL, $fontSize = NULL, $bgColor = NULL){
		$this->codeLen = is_null($codeLen) ? C('CODE_LEN') : $codeLen;
		$this->width = is_null($width) ? C('CODE_WIDTH') : $width;
		$this->height = is_null($height) ? C('CODE_HEIGHT') : $height;
		$this->fontColor = is_null($fontColor) ? C('CODE_COLOR') : $fontColor;
		$this->fontSize = is_null($fontSize) ? C('CODE_SIZE') : $fontSize;
		$this->bgColor = is_null($bgColor) ? C('CODE_BGCOLOR') : $bgColor;
		$this->seed = C('CODE_SEED');
		$this->fontFile = C('CODE_FONTFILE');
	}

	/**
	 * [show 显示验证码]
	 * @return [type] [description]
	 */
	public function show(){
		//1.发送头部
		header('Content-type:image/png');
		//2.创建画布 配色填色
		$this->_create_bg();
		//3.写字
		$this->_write_font();
		// //4.画干扰
		$this->_draw_trouble();
		// //6.输出
		imagepng($this->img);
		// //7.销毁
		imagedestroy($this->img);
	}
	/**
	 * [_draw_trouble 画干扰]
	 * @return [type] [description]
	 */
	private function _draw_trouble(){
		//画点
		for ($i=0; $i < 500; $i++) { 
			$color = imagecolorallocate($this->img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			imagesetpixel($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
		}

		//画线
		for ($i=0; $i < 10; $i++) { 
			$color = imagecolorallocate($this->img, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			imageline($this->img, mt_rand(0,$this->width), mt_rand(0,$this->height), mt_rand(0,$this->width), mt_rand(0,$this->height), $color);
		}
	}
	/**
	 * [_write_font 写字]
	 * @return [type] [description]
	 */
	private function _write_font(){
		$color = hexdec($this->fontColor);
		//验证码临时字符串
		$tempStr = '';
		//循环写字
		for ($i=0; $i < $this->codeLen; $i++) {
			$s = mt_rand(0,strlen($this->seed)-1); 
			$text = $this->seed[$s];
			//连接到临时字符串里面
			$tempStr .= $text;
			//坐标
			$x = ($this->width / $this->codeLen) * $i + 10;
			$y = ($this->height + $this->fontSize) / 2;
			//写字
			imagettftext($this->img, $this->fontSize, mt_rand(-45,45), $x, $y, $color, $this->fontFile, $text);
		}
		
		session_id() || session_start();
		//要把$tempStr存到一个介质 session？
		$_SESSION['code'] = strtoupper($tempStr);
	}

	/**
	 * [_create_bg 创建背景]
	 * @return [type] [description]
	 */
	private function _create_bg(){
		$img = imagecreatetruecolor($this->width, $this->height);
		//将16进制转为10进制
		$bgColor = hexdec($this->bgColor);
		imagefill($img, 0, 0, $bgColor);
		//保存到属性里面
		$this->img = $img;
	}

}